﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Microsoft.Practices.Composite.Presentation.Regions;
using Microsoft.Practices.Composite.Regions;
using System.Collections.Specialized;
using Microsoft.Practices.Composite;
using System.Windows;

namespace Douban.Core.Regions
{
    public class GridRegionAdapter : RegionAdapterBase<Grid>
    {
        private Grid _regionTarget;

        public GridRegionAdapter(IRegionBehaviorFactory factory) : base(factory) { }

        protected override void Adapt(IRegion region, Grid regionTarget)
        {
            _regionTarget = regionTarget;

            region.Views.CollectionChanged += OnViewChanged;
            region.ActiveViews.CollectionChanged += OnActiveViewsChanged;
        }

        private void OnActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            UIElement activeView = e.NewItems[0] as UIElement;
            if (activeView == null) return;

            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                if (activeView.Visibility != Visibility.Visible)
                    activeView.Visibility = Visibility.Visible;

            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                if (activeView.Visibility != Visibility.Hidden)
                    activeView.Visibility = Visibility.Hidden;
            }
        }

        private void OnViewChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            foreach (var view in e.NewItems)
            {
                UIElement childItem = view as UIElement;

                if (childItem == null) continue;

                if (e.Action == NotifyCollectionChangedAction.Add)
                    _regionTarget.Children.Add(childItem);
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                    _regionTarget.Children.Remove(childItem);

            }
        }

        protected override IRegion CreateRegion()
        {
            return new SingleActiveRegion();
        }
    }
}
